package com.mfs.proxy.core.server.registry;

import com.mfs.common.constant.Constant;
import com.mfs.common.utills.Assert;
import com.mfs.proxy.core.client.ProxyClient;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 代理客户端注册中心默认实现
 *
 * @author mfs
 * @date 2023/7/1 14:31
 **/
public abstract class AbstractProxyClientRegistry implements ProxyClientRegistry {
    /**
     * key proxyIp:proxyPort
     * */
    protected Map<String, ProxyClient> address2ProxyClient = new ConcurrentHashMap<>();

    @Override
    public boolean register(String proxyIp, Integer proxyPort, ProxyClient proxyClient) {
        String address = getAddress(proxyIp, proxyPort);
        ProxyClient client = address2ProxyClient.putIfAbsent(address, proxyClient);
        return true;
    }

    @Override
    public boolean unregister(String proxyIp, Integer proxyPort) {
        ProxyClient remove = address2ProxyClient.remove(getAddress(proxyIp, proxyPort));
        if (remove != null) {
            try {
                remove.close();
            } catch (IOException e) {

            }
        }
        return true;
    }

    @Override
    public ProxyClient checkout(String proxyIp, Integer proxyPort) {
        return address2ProxyClient.get(getAddress(proxyIp, proxyPort));
    }

    protected String getAddress(String proxyIp, Integer proxyPort) {
        Assert.notNull(proxyIp, "proxyIp can‘t be null");
        Assert.notNull(proxyPort, "proxyIp can‘t be null");
        return proxyIp + Constant.COLON + proxyPort.toString();
    }
}
